<template>
  <div class="com-container">
    <div class="com-chart" ref="time_ref">
    </div>
  </div>
</template>

<script>

export default {
  name: 'TimeLine',
  data () {
    return {
      chartInstance: null,//图标实例
      allData: null,//图表数据
      size: null,//大小
      currentIndex: 0,//当前所展示的一级分类的数据
      key: 0,
      currentYear: 0,
      startPoint: 0,
      lineWidth: 64,
    }
  },
  mounted () {
    this.initChart()
    //增加屏幕大小变化监听的事件
    window.addEventListener('resize', this.screenAdapter)
    this.screenAdapter()
  },
  destroyed () {
    window.removeEventListener('resize', this.screenAdapter)
  },
  watch: {
    startPoint (newVal, oldVal) {
      const arr = []
      const currentYear = new Date().getFullYear()
      if (newVal < currentYear) {
        for (let i = 0; i < currentYear; i++) {
          arr.push(i)
        }
        const option = {
          timeline: {
            data: arr
          }
        }
        this.chartInstance.setOption(option)
      }
    }
  },
  methods: {
    initChart () {
      const yearData = []
      const currentYear = new Date().getFullYear()
      for (let i = 0; i < currentYear; i++) {
        yearData.push(i.toString())
      }
      this.chartInstance = this.$echarts.init(this.$refs.time_ref, 'dark')
      const initOption = {
        timeline: {
          data: yearData,
          axisType: 'category',
          symbol: 'circle',
          label: {
            color: 'green',
            fontWeight: 'bold'
          },
          left: '1%',
          right: '1%',
          itemStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0,
                color: 'orange' // 0% 处的颜色
              }, {
                offset: 1,
                color: 'green' // 100% 处的颜色
              }],
              global: false // 缺省为 false
            }
          },
          checkpointStyle: {
            color: 'yellow'
          },
          controlStyle: {
            showPlayBtn: false
          },
          progress: {
            lineStyle: {},
            itemStyle: {
              color: '#74C9F3'
            }
          }
        },
      }
      this.chartInstance.setOption(initOption, 'dark')
      this.chartInstance.on('timelinechanged', this.timeLineChanged)
    },
    screenAdapter () {
      this.size = document.documentElement.clientHeight
      this.lineWidth = this.size / 14
      const adaptOption = {
        timeline: {
          left: '1%',
          right: '1%'
        }
      }
      this.chartInstance.setOption(adaptOption)
      this.chartInstance.resize()
    },
    timeLineChanged (res) {
      this.currentYear = res.currentIndex
    }
  },
}
</script>

<style scoped>
.com-chart {
  /*height: 60px;*/
  width: 100%;
}
</style>
